//Scripts

var tweetPhoenix = {
tweetPhoenix.chirps = [];
tweetPhoenix.profile = [];
tweetPhoenix.friends = [];
tweetPhoenix.url = "https://tweetphoenix.firebaseio.com/";
tweetPhoenix.urlProfile = "https://tweetphoenix.firebaseio.com/profile/";
tweetPhoenix.urlFriends = "https://tweetphoenix.firebaseio.com/friends/";
tweetPhoenix.Profile = function (name, image, bio) {
    this.name = name;
    this.image = image;
    this.bio = bio;
};
tweetPhoenix.Friend = function (url) {
    this.url = url;
};

//url Helper Function
tweetPhoenix.urlHelper = function () {
    var url = tweetPhoenix.url;
    //Need to Loop through Arguements of url
    for (var i in arguments) {
        url += arguments[i] + "/";
   
        return url + ".json";
    };
    tweetPhoenix.friendUrlHelper = function () {
        var url = tweetPhoenix.urlFriends;
        //Need to Loop through Arguements of url
        for (var i in arguments) {
            url += arguments[i] + "/";
        }
        return url + ".json";
    };
    tweetPhoenix.profileUrlHelper = function () {
        var url = tweetPhoenix.urlProfile;
        //Need to Loop through Arguements of url
        for (var i in arguments) {
            url += arguments[i] + "/";
        }
        return url + ".json";
    };
    //AJAX Utility Function
    tweetPhoenix.Ajax = function (method, url, SendingData, Success) {
        var request = new XMLHttpRequest();
        request.open(method, url);
        request.onload = function () {
            if (this.status >= 200 && this.status <= 400) {
                //Do success things
                var data = JSON.parse(this.response);
                Success(data);
            }
            else {
                console.log("Error: on " + Method + " sent to " + url + this.response);
            }
        };
        request.onerror = function () {
            console.log("Comm error on " + Method + " sent to " + url);
        };
        if (SendingData) {
            //only stringifys if valid data has been passed
            SendingData = JSON.stringify(SendingData);
        }
        request.send(SendingData);
    };
    //AJAX Helper Functions
    tweetPhoenix.Get = function (url, Success) {
        tweetPhoenix.Ajax("GET", url, null, Success);
    };
    tweetPhoenix.Post = function (url, SendingData, Success) {
        tweetPhoenix.Ajax("POST", url, SendingData, Success);
    };
    tweetPhoenix.Delete = function (url, Success) {
        tweetPhoenix.Ajax("DELETE", url, null, Success);
    };
    tweetPhoenix.Patch = function (url, SendingData, Success) {
        tweetPhoenix.Ajax("PATCH", url, SendingData, Success);
    };
    //CREATE Chirps
    tweetPhoenix.AddChirp = function () {
        var time = Date.now();
        var chirp = {};
        timestamp = new Date(time);
        chirp.timestamp = timestamp.toLocaleTimeString();
        chirp.text = document.getElementById("Text").value;
        chirp.author = document.getElementById("Author").value;
        var index = tweetPhoenix.Chirps.push(chirp) - 1;
        tweetPhoenix.SortChirps();
        tweetPhoenix.WriteChirps();
        tweetPhoenix.Post(tweetPhoenix.urlHelper(), chirp,
            function (key) {
                var holder = tweetPhoenix.Chirps[index];
                holder.key = key.name;
            });
        document.getElementById("Text").value = "";
    };

    //CREATE TextBox Limiter
    $(function(){
        $("#demo").characterCounter({
 
            exceeded: false,
            renderTotal: false,
            increaseCounting: false,
            limit: 140, 
            counterSelector: false,       
            counterWrapper: 'span',        
            counterCssClass: 'help-block',         
            counterFormat: 'Characters Remaining: %1',  
            counterExceededCssClass: 'exceeded',         
            onExceed: function(count) {},      
            onDeceed: function(count) {},           
            customFields: {}
 
        }); 
    });

    //CREATE Friend
    tweetPhoenix.AddFriend = function () {
        var url = document.getElementById("AddFriend").value;
        var friend = new tweetPhoenix.Friend(url);
        var index = tweetPhoenix.Friends.push(friend) - 1;
        tweetPhoenix.WriteFriends();
        tweetPhoenix.Post(tweetPhoenix.FriendurlHelper(), friend,
            function (key) {
                var holder = tweetPhoenix.Friends[index];
                holder.key = key.name;
                //tweetPhoenix.WriteFriends();
            });
        document.getElementById("AddFriend").value = "";
    };
    //GET Chirps
    tweetPhoenix.GetChirps = function () {
        tweetPhoenix.Get(tweetPhoenix.urlHelper(),
            function (allChirps) {
                //setTimeout(tweetPhoenix.GetChirps, 3000);
                for (var i in allChirps) {
                    allChirps[i].key = i;
                    tweetPhoenix.Chirps.push(allChirps[i]);
                }
                //INSERT SORT FUNCTION HERE
                tweetPhoenix.Chirps.sort(
                    function (a, b) {
                        if (a.timestamp < b.timestamp) {
                            return 1;
                        }
                        else {
                            return -1;
                        }
                    });
                tweetPhoenix.WriteChirps();
            });
        console.log("GET sent:" + Date.now());
    };
    tweetPhoenix.GetChirps();
    //GET Friends
    tweetPhoenix.GetFriends = function () {
        tweetPhoenix.Get(tweetPhoenix.FriendurlHelper(),
                function (allFriends) {
                    for (var i in allFriends) {
                        allFriends[i].key = i;
                        tweetPhoenix.Friends.push(allFriends[i]);
                    }
                    //INSERT SORT FUNCTION HERE
                    tweetPhoenix.Friends.sort(
                        function (a, b) {
                            if (a.timestamp < b.timestamp) {
                                return 1;
                            }
                            else {
                                return -1;
                            }
                        });
                    tweetPhoenix.WriteFriends();
                });
    };
    tweetPhoenix.GetFriends();
    //GET Friend Chirps
    tweetPhoenix.GetFriendChirps = function () {
    };
    //SORT Chirps
    tweetPhoenix.SortChirps = function () {
        tweetPhoenix.Chirps.sort(
            function (a, b) {
                if (a.timestamp < b.timestamp) {
                    return 1;
                }
                else {
                    return -1;
                }
            });
        tweetPhoenix.WriteChirps();
    };
    //WRITE Chirps to DOM
    tweetPhoenix.WriteChirps = function () {
        var holder = "";
        for (i in tweetPhoenix.Chirps) {
            holder += "<div>";
            for (i in tweetPhoenix.Chirps[i]) {
                holder += "<div>" + tweetPhoenix.Chirps[i][i] + "</div>";
            }
            holder += "<div><button type='button' class='btn btn-danger' onclick='tweetPhoenix.DeleteChirp(\"" + i + "\")'>Delete this Chirp</button></div><br/>";
        }
        holder += "</div>";
        document.getElementById("myChirpsOutput").innerHTML = holder;
    };
    //WRITE Friends List to DOM
    tweetPhoenix.WriteFriends = function () {
        var holder = "";
        for (var i in tweetPhoenix.Friends) {
            holder += "<ul>";
            for (i in tweetPhoenix.Friends[i]) {
                holder += "<li>" + tweetPhoenix.Friends[i][i] + "</li>";
            }
            holder += "<div class='btn btn-danger' onclick='tweetPhoenix.DeleteFriend(\"" + i + "\")'>Delete this Friend</div><br/>";
            holder += "<div class='btn btn-default' onclick='tweetPhoenix.GetFriendChirps(\"" + i + "\")'>View Chirp Feed</div><br/>";
        }
        holder += "</ul>";
        document.getElementById("myFriendsList").innerHTML = holder;
    };
    //DELETE Chirp
    tweetPhoenix.DeleteChirp = function (index) {
        tweetPhoenix.Delete(tweetPhoenix.urlHelper(tweetPhoenix.Chirps[index].key),
            function () {
                //remove from Array with splice and remove just 1
                tweetPhoenix.Chirps.splice(index, 1);
                //WRITE data to the document
                tweetPhoenix.WriteChirps();
            });
    };
    //DELETE Friend
    tweetPhoenix.DeleteFriend = function (index) {
        tweetPhoenix.Delete(tweetPhoenix.FriendurlHelper(tweetPhoenix.Friends[index].key),
            function () {
                //remove from Array with splice and remove just 1
                tweetPhoenix.Friends.splice(index, 1);
                //WRITE data to the document
                tweetPhoenix.WriteFriends();
            });
    };
    //CREATE Profile
    //PATCH Profile data
    tweetPhoenix.AddProfile = function () {
        var profile = {
            name: document.getElementById("ProfileName").value,
            image: document.getElementById("ProfileImage").value,
            bio: document.getElementById("ProfileBio").value
        }
        tweetPhoenix.Post(tweetPhoenix.urlProfile + ".json", profile,
            function () {
                tweetPhoenix.Profile.name = profile.name;
                tweetPhoenix.Profile.image = profile.image;
                tweetPhoenix.Profile.bio = profile.bio;
            });
        //document.getElementById("myProfileName").value = profile.name;
        //document.getElementById("myProfileName").innerText = "<h4>" + profile.name + "</h4>";
        //document.getElementById("Author").value = profile.name;
        //document.getElementById("myProfileImage").innerHTML = "<img src='" + profile.image + "'/>";
        //document.getElementById("myProfileBio").value = profile.bio;
        //document.getElementById("myProfileBio").innerText = "<h2>" + profile.bio + "</h2>";
    };
    //PATCH Profile data
    tweetPhoenix.SaveUpdateProfile = function () {
        var profile = {
            name: document.getElementById("ProfileName").value,
            image: document.getElementById("ProfileImage").value,
            bio: document.getElementById("ProfileBio").value
        }
        tweetPhoenix.Patch(tweetPhoenix.urlProfile + ".json", profile,
            function () {
                tweetPhoenix.Profile.name = profile.name;
                tweetPhoenix.Profile.image = profile.image;
                tweetPhoenix.Profile.bio = profile.bio;
            });
        document.getElementById("myProfileName").value = profile.name;
        document.getElementById("myProfileName").innerText = "<h4>" + profile.name + "</h4>";
        document.getElementById("Author").value = profile.name;
        document.getElementById("myProfileImage").innerHTML = "<img src='" + profile.image + "'/>";
        document.getElementById("myProfileBio").value = profile.bio;
        document.getElementById("myProfileBio").innerText = "<h2>" + profile.bio + "</h2>";
        $('#EditProfileModal').modal('hide');
    };
    //DISPLAY Profile Modal
    tweetPhoenix.ShowUpdateProfile = function () {
        //tweetPhoenix.Get(tweetPhoenix.urlProfile + ".json",
        //    function () {
        //        tweetPhoenix.Profile.name = profile.name;
        //        tweetPhoenix.Profile.image = profile.image;
        //        tweetPhoenix.Profile.bio = profile.bio;
        //    });
        //document.getElementById("myProfileName").value = profile.name;
        //document.getElementById("myProfileImage").value = profile.image;
        //document.getElementById("myProfileBio").value = profile.bio;
        //document.getElementById("EditProfileTitle").innerHTML = "Editing " + profile.name;
        $('#EditProfileModal').modal();
    };

    tweetPhoenix.ChirpDeck = $(document).ready(function () {
        $('li').click(function () {
            var number = $(this).index();
            $('#pill-content div').hide().eq(number).show();
            $(this).toggleClass('active inactive');
            $('li').not(this).removeClass('active').addClass('inactive');
        });
        $('#pill-content div').not(':first').hide();

    });
};